package com.ruoyi.web.controller.api.team;

import com.ruoyi.base.domain.BaseLimit;
import com.ruoyi.base.service.IBaseLimitService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.data.domain.DataGold;
import com.ruoyi.data.domain.DataScore;
import com.ruoyi.data.domain.DataUserRelation;
import com.ruoyi.data.domain.TeamExamUser;
import com.ruoyi.data.service.IDataGoldService;
import com.ruoyi.data.service.IDataScoreService;
import com.ruoyi.data.service.IDataUserRelationService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zzp
 * @version 1.0.0
 * @ClassName IndexController.java
 * @Description 积分接口
 * @createTime 2022年10月09日 16:05:00
 */
@Api("获取团队成员接口")
@RestController
@RequestMapping("/api/team")
public class TeamController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IDataScoreService scoreService;

    @Autowired
    private IDataGoldService goldService;

    @Autowired
    private IDataUserRelationService userRelationService;

    @Autowired
    private IBaseLimitService limitService;

    @ApiOperation("获取团队成员")
    @GetMapping("/teamList")
    public TableDataInfo teamList(SysUser user) {
        startPage();
        user.setStatus("0");
        List<SysUser> list = userService.selectExamUserList(user);
        return getDataTable(list);
    }

    @ApiOperation("获取审核成员列表")
    @GetMapping("/examList")
    public TableDataInfo examList(SysUser user) {
        startPage();
        user.setStatus("1");
        List<SysUser> list = userService.selectExamUserList(user);
        return getDataTable(list);
    }

    @ApiOperation("审核会员")
    @PutMapping("/examUser/{userId}")
    @Log(title = "审核会员", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult examUser(@PathVariable Long userId) {
        SysUser user = userService.selectUserById(userId);
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("审核会员失败，会员不存在");
        }
        if (user.getStatus().equals("0")) {
            return AjaxResult.error("审核会员失败，会员已审核");
        }
        SysUser examUser = userService.selectUserById(getUserId());
        if (examUser.getUserAvailable() == 0) {
            return AjaxResult.error("审核会员失败，您的审核名额不足");
        }
        // 计算积分
        BaseLimit limit = limitService.selectBaseLimitUse();
        if (examUser.getGoldAvailable() < Integer.parseInt(limit.getGoldScale())) {
            return AjaxResult.error("您的可用金豆不足");
        }
        examUser.setGoldAvailable(examUser.getGoldAvailable() - Integer.parseInt(limit.getGoldScale()));

        //扣减金豆
        DataGold gold = new DataGold();
        goldChange("审核会员", user, examUser, limit, gold, 1);

        user.setStatus("0");
        userService.updateUserProfile(user);
        examUser.setUserAvailable(examUser.getUserAvailable() - 1);
        userService.updateUserProfile(examUser);
        SysDept dept = deptService.selectDeptById(user.getDeptId());
        dept.setStatus("0");
        deptService.updateDeptProfile(dept);

        DataScore dataScore;

        // 限制层级
        int limitLevel = Integer.parseInt(limit.getLimitLevel());
        // 限制分层
        int limitMax = Integer.parseInt(limit.getLimitMax());
        // 分层数量
        int maxNum = Integer.parseInt(limit.getMaxNum());
        // 限制天数
        int limitDay = Integer.parseInt(limit.getLimitDay());
        // 是否跳过
        String jump = limit.getJump();
        // 相差天数
        int days;
        SysUser topUser = new SysUser();
        boolean addAgain = true;
        DataUserRelation userRelation;
        for (int i = 0; i < limitLevel; i++) {
            if (i == 0) {
                userRelation = userRelationService.selectDataUserRelationByUserId(user.getUserId());
            } else {
                userRelation = userRelationService.selectDataUserRelationByUserId(topUser.getUserId());
            }
            if (StringUtils.isNotNull(topUser)) {
                if (userRelation.getTopUserId() == 1L) {
                    break;
                }
            }
            if (StringUtils.isNull(userRelation)) {
                break;
            }
            topUser = userService.selectUserById(userRelation.getTopUserId());
            if (jump.equals("Y") && topUser.getStatus().equals("1")) {
                continue;
            }
            if (StringUtils.isNull(topUser.getLoginDate())) {
                days = DateUtils.differentDaysByMillisecond(topUser.getCreateTime(), DateUtils.getNowDate());
            } else {
                days = DateUtils.differentDaysByMillisecond(topUser.getLoginDate(), DateUtils.getNowDate());
            }
            if (days > limitDay) {
                continue;
            }
            dataScore = new DataScore();
            if (limitMax > i) {
                //获取分层数量
                dataScore.setScore(maxNum);
            } else {
                //获取1积分
                dataScore.setScore(1);
            }
            dataScore.setDeptId(topUser.getDeptId());
            dataScore.setUserId(topUser.getUserId());
            dataScore.setNickName(topUser.getNickName());
            dataScore.setScoreType("in");
            dataScore.setScoreDesc(StringUtils.format("恭喜您获得【{}】积分!【{}】加入系统！【{}】审核通过！审核时间：{}",
                    dataScore.getScore(),
                    user.getNickName(),
                    examUser.getNickName(),
                    DateUtils.getTime()));
            topUser.setScoreAll(topUser.getScoreAll() + dataScore.getScore());
            topUser.setScoreAvailable(topUser.getScoreAvailable() + dataScore.getScore());
            userService.updateUserProfile(topUser);
            dataScore.setScoreCurrent(topUser.getScoreAvailable());
            dataScore.setCreateBy(examUser.getUserName());
            scoreService.insertDataScore(dataScore);

            if (addAgain) {
                if (topUser.getUserId().longValue() == examUser.getUserId().longValue()) {
                    addAgain = false;
                }
            }
        }

        if (addAgain) {
            // 给审核人添加积分
            dataScore = new DataScore();
            dataScore.setScore(1);
            dataScore.setDeptId(examUser.getDeptId());
            dataScore.setUserId(examUser.getUserId());
            dataScore.setNickName(examUser.getNickName());
            dataScore.setScoreType("in");
            dataScore.setScoreDesc(StringUtils.format("恭喜您获得【{}】积分!【{}】加入系统！【{}】审核通过！审核时间：{}",
                    dataScore.getScore(),
                    user.getNickName(),
                    examUser.getNickName(),
                    DateUtils.getTime()));
            examUser.setScoreAll(examUser.getScoreAll() + dataScore.getScore());
            examUser.setScoreAvailable(examUser.getScoreAvailable() + dataScore.getScore());
            userService.updateUserProfile(examUser);
            dataScore.setScoreCurrent(examUser.getScoreAvailable());
            dataScore.setCreateBy(examUser.getUserName());
            scoreService.insertDataScore(dataScore);
        }
        return AjaxResult.success();
    }

    @ApiOperation("二次消费")
    @PutMapping("/againExam")
    @Log(title = "二次消费", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult againExam(@RequestBody TeamExamUser againExam) {
        SysUser user = userService.selectUserById(againExam.getUserId());
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("二次消费失败，会员不存在");
        }
        SysUser examUser = userService.selectUserById(getUserId());
        if (examUser.getUserAvailable() < againExam.getUserNumber()) {
            return AjaxResult.error("二次消费失败，您的可用名额不足可用名额为:" + examUser.getUserAvailable());
        }
        // 计算积分
        BaseLimit limit = limitService.selectBaseLimitUse();
        if (examUser.getGoldAvailable() < Integer.parseInt(limit.getGoldScale()) * againExam.getUserNumber()) {
            return AjaxResult.error("您的可用金豆不足");
        }
        examUser.setGoldAvailable(examUser.getGoldAvailable() - (Integer.parseInt(limit.getGoldScale()) * againExam.getUserNumber()));
        DataGold gold = new DataGold();
        //扣减金豆
        goldChange("二次消费", user, examUser, limit, gold, againExam.getUserNumber());

        examUser.setUserAvailable(examUser.getUserAvailable() - againExam.getUserNumber());
        userService.updateUserProfile(examUser);

        // 限制层级
        int limitLevel = Integer.parseInt(limit.getLimitLevel());
        // 限制分层
        int limitMax = Integer.parseInt(limit.getLimitMax());
        // 分层数量
        int maxNum = Integer.parseInt(limit.getMaxNum());
        // 限制天数
        int limitDay = Integer.parseInt(limit.getLimitDay());
        // 是否跳过
        String jump = limit.getJump();
        // 相差天数
        int days;
        SysUser topUser = new SysUser();
        DataUserRelation userRelation;
        DataScore dataScore;
        for (int i = 0; i < limitLevel; i++) {
            if (i == 0) {
                userRelation = userRelationService.selectDataUserRelationByUserId(user.getUserId());
            } else {
                userRelation = userRelationService.selectDataUserRelationByUserId(topUser.getUserId());
            }
            if (StringUtils.isNotNull(topUser)) {
                if (userRelation.getTopUserId() == 1L) {
                    break;
                }
            }
            if (StringUtils.isNull(userRelation)) {
                break;
            }
            topUser = userService.selectUserById(userRelation.getTopUserId());
            if (jump.equals("Y") && topUser.getStatus().equals("1")) {
                continue;
            }
            if (StringUtils.isNull(topUser.getLoginDate())) {
                days = DateUtils.differentDaysByMillisecond(topUser.getCreateTime(), DateUtils.getNowDate());
            } else {
                days = DateUtils.differentDaysByMillisecond(topUser.getLoginDate(), DateUtils.getNowDate());
            }
            if (days > limitDay) {
                continue;
            }
            dataScore = new DataScore();
            if (limitMax > i) {
                // 获取分层数量*二次消费数量
                dataScore.setScore(maxNum * againExam.getUserNumber());
            } else {
                // 获取二次消费数量
                dataScore.setScore(againExam.getUserNumber());
            }
            dataScore.setDeptId(topUser.getDeptId());
            dataScore.setUserId(topUser.getUserId());
            dataScore.setNickName(topUser.getNickName());
            dataScore.setScoreType("in");
            dataScore.setScoreDesc(StringUtils.format("恭喜您获得【{}】积分!【{}】二次消费{}次！二次消费时间：{}",
                    dataScore.getScore(),
                    user.getNickName(),
                    againExam.getUserNumber(),
                    DateUtils.getTime()));
            topUser.setScoreAll(topUser.getScoreAll() + dataScore.getScore());
            topUser.setScoreAvailable(topUser.getScoreAvailable() + dataScore.getScore());
            userService.updateUserProfile(topUser);
            dataScore.setScoreCurrent(topUser.getScoreAvailable());
            dataScore.setCreateBy(examUser.getUserName());
            scoreService.insertDataScore(dataScore);
        }
        // 给审核人添加积分
        dataScore = new DataScore();
        dataScore.setScore(1);
        dataScore.setDeptId(examUser.getDeptId());
        dataScore.setUserId(examUser.getUserId());
        dataScore.setNickName(examUser.getNickName());
        dataScore.setScoreType("in");
        dataScore.setScoreDesc(StringUtils.format("恭喜您获得【{}】积分!【{}】加入系统！【{}】审核通过！审核时间：{}",
                dataScore.getScore(),
                user.getNickName(),
                examUser.getNickName(),
                DateUtils.getTime()));
        examUser.setScoreAll(examUser.getScoreAll() + dataScore.getScore());
        examUser.setScoreAvailable(examUser.getScoreAvailable() + dataScore.getScore());
        userService.updateUserProfile(examUser);
        dataScore.setScoreCurrent(examUser.getScoreAvailable());
        dataScore.setCreateBy(examUser.getUserName());
        scoreService.insertDataScore(dataScore);
        return AjaxResult.success();
    }

    @ApiOperation("删除会员")
    @PutMapping("/deleteUser/{userId}")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deleteUser(@PathVariable Long userId) {
        SysUser user = userService.selectUserById(userId);
        userService.deleteUserById(userId);
        deptService.deleteDeptById(user.getDeptId());
        return AjaxResult.success();
    }

    /**
     * 扣减金豆
     *
     * @param user
     * @param examUser
     * @param limit
     * @param gold
     * @param userNumber
     */
    private void goldChange(String typeName, SysUser user, SysUser examUser, BaseLimit limit, DataGold gold, Integer userNumber) {
        gold.setDeptId(examUser.getDeptId());
        gold.setUserId(examUser.getUserId());
        gold.setNickName(examUser.getNickName());
        gold.setGold(Integer.parseInt(limit.getGoldScale()) * userNumber);
        gold.setGoldCurrent(examUser.getGoldAvailable());
        gold.setGoldType("out");
        gold.setGoldDesc(StringUtils.format("{}减少：{}金豆。{}名称:{}---审核人：【{}】---审核时间：【{}】",
                typeName,
                gold.getGold(),
                typeName,
                user.getNickName(),
                examUser.getNickName(),
                DateUtils.getTime()));
        gold.setCreateBy(user.getUserName());
        goldService.insertDataGold(gold);
    }
}